import { Command } from '../constant';
import Taro from '@tarojs/taro';
import { Dispatch } from 'typings';
import { IAllReducerProps } from '../types';
import { getReducerData } from '@/redux/store';
import { extraPathsValue } from '@/redux/util';
import api from 'api';
export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async goToWeixinPay(openid) {
      const {
        main: { selectCard },
      } = getData();

      try {
        const context = await api.payController.wxPayPurchaseCardOrderForLittleProgram({ openid, cardId:selectCard });
        // @ts-ignore
        const { timeStamp, nonceStr, signType, paySign } = context;
        await Taro.requestPayment({
          timeStamp,
          nonceStr,
          // @ts-ignore
          package: context.package,
          signType,
          paySign,
          success: async () => {
            let back = false
            Taro.showToast({
              title: '会员续费成功!',
              icon: 'none',
            });
            let task = Taro.getStorageSync("task");
            if (task) task = JSON.parse(task)
            if (task && task.taskInfoVO.conditionsType == 6) {
              await api.TaskCenterController.completedTask({
                id: task.id
              });
              Taro.removeStorageSync("task")
              setTimeout(() => {
                Taro.showToast({
                  title: `获得${task.taskInfoVO.rewardType == 0 ? task.taskInfoVO.rewardPoints : ""}${["积分", "优惠券", "实物商品"][task.taskInfoVO.rewardType]}${task.taskInfoVO.rewardType == 2 ? "请到我的-我的奖励中填写收货地址":""}`,
                  icon: 'none',
                });
                back = true
              }, 1000)
            }
            setTimeout(() => {
              if (back) {
                Taro.navigateBack()
              } else {
                Taro.switchTab({
                  url: '/pages/index/index',
                });
              }
            }, 2000)

          },
          fail: function () { },
        });
      } catch (e) {
        console.log(e);
      }
    },
    async getMemberBase() {
      const result = await api.MemberController.getMemberBase();
      let memberCardType = 'noMember';
      if (result.isAquamarineMember) {
        memberCardType = 'lanjing';
      }
      if (result.isCrystalMember) {
        memberCardType = 'chijing';
      }
      if (result.isAquamarineMember && result.isCrystalMember) {
        memberCardType = 'shuangchong';
      }
      dispatch({
        type: Command.init,
        payload: {
          main: {
            memberCardType,
            memberInfo: result,
          },
        },
      });
      return memberCardType;
    },
    async page() {
      const memberCardType = await this.getMemberBase();
      const result = await api.MemberOpenController.getOpenMemberList({});
      if (Array.isArray(result)) {
        const lanjingList = [];
        const chijingList = [];
        result.forEach((e) => {
          (e.memberType == 0 ? lanjingList : chijingList).push(e);
        });
        action.commonChange('main.lanjingList', lanjingList);
        action.commonChange('main.chijingList', chijingList);
        if (lanjingList && chijingList) {
          if (['noMember', 'lanjing'].includes(memberCardType)) {
            action.commonChange('main.selectCard', lanjingList[0].cardId);
            action.commonChange('main.selectCardMoney', lanjingList[0].activityPrice);

          } else {
            action.commonChange('main.selectCard', chijingList[0].cardId);
            action.commonChange('main.selectCardMoney', chijingList[0].activityPrice);


          }
        }
      }
    },
    /**
     * 初始化
     */
    async query() { },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageArenewalMemberMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
